package com.WebMentorPro.system.controller;

import com.WebMentorPro.system.annotation.AuthCheck;
import com.WebMentorPro.system.common.BaseResponse;
import com.WebMentorPro.system.common.DeleteRequest;
import com.WebMentorPro.system.common.ErrorCode;
import com.WebMentorPro.system.common.ResultUtils;
import com.WebMentorPro.system.constant.UserConstant;
import com.WebMentorPro.system.exception.BusinessException;
import com.WebMentorPro.system.exception.ThrowUtils;
import com.WebMentorPro.system.model.dto.expertReading.ExpertAddRequest;
import com.WebMentorPro.system.model.dto.expertReading.ExpertQueryByMyRequest;
import com.WebMentorPro.system.model.dto.expertReading.ExpertQueryRequest;
import com.WebMentorPro.system.model.dto.expertReading.ExpertUpdateRequest;
import com.WebMentorPro.system.model.entity.ExpertReading;
import com.WebMentorPro.system.model.entity.Teacher;
import com.WebMentorPro.system.model.entity.User;
import com.WebMentorPro.system.model.vo.ExpertReadingVO;
import com.WebMentorPro.system.model.vo.LoginUserVO;
import com.WebMentorPro.system.service.ExpertReadingService;
import com.WebMentorPro.system.service.TeacherService;
import com.WebMentorPro.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 大咖阅读接口
 *
 * @author bianxinyao
 */
@RestController
@RequestMapping("/expertReading")
@Slf4j
@Api(tags = {"大咖阅读接口"})
public class ExpertReadingController {

    @Resource
    private UserService userService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private ExpertReadingService expertReadingService;

    // region 登录相关

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    /**
     * 获取当前登录异科导师
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login/teacher")
    @ApiOperation(value = "获取当前登录异科导师")
    public BaseResponse<Teacher> getLoginTeacher(HttpServletRequest request) {
        Teacher teacher = teacherService.getLoginTeacher(request);
        return ResultUtils.success(teacher);
    }

    // endregion

    // region 增删改查

    /**
     * 创建大咖阅读记录
     *
     * @param expertAddRequest
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建大咖阅读记录")
    public BaseResponse<Long> addAdminNotification(@RequestBody ExpertAddRequest expertAddRequest, HttpServletRequest request) {
        if (expertAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userService.getLoginUser(request).getId();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        User one = userService.getOne(queryWrapper);
        ExpertReading expertReading = new ExpertReading();
        expertReading.setStudentId(id);
        expertReading.setTeacherId(one.getTeacherId());
        BeanUtils.copyProperties(expertAddRequest, expertReading);
        boolean result = expertReadingService.save(expertReading);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建大咖阅读记录表创建失败");
        return ResultUtils.success(expertReading.getId());
    }

    /**
     * 删除大咖阅读记录（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除大咖阅读记录（仅管理员）")
    public BaseResponse<Boolean> deleteNotification(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        boolean result = expertReadingService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除大咖阅读记录失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新大咖阅读记录
     *
     * @param expertUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新大咖阅读记录")
    public BaseResponse<Boolean> updateNotification(@RequestBody ExpertUpdateRequest expertUpdateRequest, HttpServletRequest request) {
        if (expertUpdateRequest == null || expertUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userService.getLoginUser(request).getId();
        ExpertReading expertReading = new ExpertReading();
        QueryWrapper<ExpertReading> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", expertUpdateRequest.getId());
        ExpertReading one = expertReadingService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "大咖阅读记录不存在");
        }
        if (expertUpdateRequest.getBookTitle() == null || expertUpdateRequest.getBookTitle().equals("")) {
            expertUpdateRequest.setBookTitle(one.getBookTitle());
        }
        if (expertUpdateRequest.getBookType() == null || expertUpdateRequest.getBookType().equals("")) {
            expertUpdateRequest.setBookType(one.getBookType());
        }
        if (expertUpdateRequest.getReadingTime() == 0) {
            expertUpdateRequest.setReadingTime(one.getReadingTime());
        }
        if (expertUpdateRequest.getReadingDate() == null || expertUpdateRequest.getReadingDate().equals("")) {
            expertUpdateRequest.setReadingDate(one.getReadingDate());
        }
        BeanUtils.copyProperties(expertUpdateRequest, expertReading);
        boolean result = expertReadingService.updateById(expertReading);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新大咖阅读记录失败");
        return ResultUtils.success(result);
    }

    /**
     * 获取全部的大咖阅读记录（仅管理员）
     *
     * @param expertQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "获取全部的大咖阅读记录（仅管理员）")
    public BaseResponse<Page<ExpertReadingVO>> getNotification(@RequestBody ExpertQueryRequest expertQueryRequest) {
        long current = expertQueryRequest.getCurrent() == 0 ? 1 : expertQueryRequest.getCurrent();
        long size = expertQueryRequest.getPageSize() == 0 ? 10 : expertQueryRequest.getPageSize();

        Page<ExpertReadingVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<ExpertReadingVO> expertReadingVOPage = expertReadingService.getQueryWrapper(pageParam, expertQueryRequest);

        return ResultUtils.success(expertReadingVOPage);
    }

    /**
     * 异科导师分页获取自己学生的大咖阅读记录
     *
     * @param examQueryByMyRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/teacher")
    @ApiOperation(value = "异科导师分页获取自己学生的大咖阅读记录")
    public BaseResponse<Page<ExpertReadingVO>> getNotificationByTeacher(@RequestBody ExpertQueryByMyRequest examQueryByMyRequest, HttpServletRequest request) {
        // 异科导师id
        Long teacherId = teacherService.getLoginTeacher(request).getId();

        long current = examQueryByMyRequest.getCurrent() == 0 ? 1 : examQueryByMyRequest.getCurrent();
        long size = examQueryByMyRequest.getPageSize() == 0 ? 10 : examQueryByMyRequest.getPageSize();

        Page<ExpertReadingVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<ExpertReadingVO> expertReadingVOPage = expertReadingService.getQueryByMyTeacher(pageParam, examQueryByMyRequest, teacherId);

        return ResultUtils.success(expertReadingVOPage);
    }

    /**
     * 学生分页获取自己的大咖阅读记录
     *
     * @param examQueryByMyRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/student")
    @ApiOperation(value = "学生分页获取自己的大咖阅读记录")
    public BaseResponse<Page<ExpertReadingVO>> getMeetingByStudent(@RequestBody ExpertQueryByMyRequest examQueryByMyRequest, HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();

        long current = examQueryByMyRequest.getCurrent() == 0 ? 1 : examQueryByMyRequest.getCurrent();
        long size = examQueryByMyRequest.getPageSize() == 0 ? 10 : examQueryByMyRequest.getPageSize();

        Page<ExpertReadingVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<ExpertReadingVO> expertReadingVOPage = expertReadingService.getQueryByMyStudent(pageParam, examQueryByMyRequest, userId);

        return ResultUtils.success(expertReadingVOPage);
    }

    // endregion
}
